/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \personnelmanage\src\pages\StatementOfAccount\SendStatementOfAccount\components\SelectDistributor.tsx
 * @Date: 2022-03-15 10:26:18
 * @LastEditTime: 2022-10-13 18:03:58
 */

import React from 'react'
import { UdTable, UdFilter, columnRenders, http, IUdColumn, UdModal } from '@/lib'
import { Modal, TreeSelect, Button, message } from 'antd'
import userApis from '@/apis'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import apis from '@/apis/StatementOfAccount/index'
import ImportExcelForm from '../components/ImportExcelForm'

const { TreeNode } = TreeSelect

export default class SelectDistributor extends React.Component<IProps> {
  private filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private conditions: any[] = [
    {
      label: '所属组织',
      id: 'belongAreaCode',
      render: () => (
        <TreeSelect showSearch treeNodeFilterProp="title">
          {this.mapTree(this.state.treeDataList)}
        </TreeSelect>
      ),
    },
    { label: '客户名称', id: 'agentName' },
    { label: '客户编码', id: 'agentCode' },
  ]
  private columns: IUdColumn<any>[] = [
    ['序号', 'id', (text, record, index) => index + 1, { width: '50px' }],
    { title: '客户编码', dataIndex: 'agentCode', minWidth: '120px' },
    { title: '客户名称', dataIndex: 'agentName', minWidth: '140px' },
    { title: '所属组织', dataIndex: 'belongAreaName', minWidth: '120px' },
    // { title: '品牌公司', dataIndex: 'brandName', minWidth: '120px' },
    {
      title: '操作',
      dataIndex: 'operate',
      fixedWidth: '40px',
      fixed: 'right',
      render: columnRenders.operate([
        {
          title: '删除',
          action: (text, record) => {
            this.handDeleteRecord(record)
          },
        },
      ]),
    },
  ]

  state: IState = {
    dataSource: [],
    pagination: {},
    treeDataList: [],
    selectedRowKeys: [],
    selectedRows: [],
    loading: false,
  }

  render() {
    let { pagination, loading, dataSource, selectedRowKeys } = this.state
    return (
      <>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={loading}
          resetAfter={this.resetFilterHandle}
        />
        <Button
          type="primary"
          style={{ marginBottom: '10px' }}
          onClick={() => {
            this.handImportExcel()
          }}
        >
          导入
        </Button>
        <UdTable
          rowKey="id"
          columns={this.columns}
          loading={loading}
          dataSource={dataSource}
          pagination={pagination}
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            onChange: this.onSelectChange,
            onSelectAll: this.onSelectAll,
          }}
          onChange={paginationOpt => {
            this.setState({ pagination: paginationOpt })
          }}
        ></UdTable>
      </>
    )
  }

  componentDidMount() {
    const { dataSource } = this.props
    if (Array.isArray(dataSource) && dataSource.length > 0) {
      this.setState({
        // dataSource,
        selectedRows: dataSource,
        selectedRowKeys: dataSource.map(({ id }) => id),
        // pagination: {
        //   current: 1,
        //   pageSize: 10,
        //   total: dataSource.length ?? 0,
        //   showSizeChanger: true,
        //   pageSizeOptions: ['10', '20', '30', '40'],
        //   showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        // },
      })
    }
    this.getAreaList(this.props.brandCode)
  }

  //导入文件
  private handImportExcel = () => {
    UdModal.open({
      title: '导入文件',
      maskClosable: false,
      content: <ImportExcelForm />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        let { file: fileList } = values
        return this.importExcel(fileList?.[0]?.originFileObj)
      },
    })
  }
  //文件上传
  private importExcel = excelFile => {
    if (!excelFile) return
    const formData = new FormData()
    formData.append('file', excelFile)
    // console.log('this.filterForm.getFieldsValue()[]', this.filterForm.getFieldsValue()['brandCode'])
    let params: any = { brandCode: this.props.brandCode }
    formData.append('agentLetterReqVo', new Blob([JSON.stringify(params)], { type: 'application/json' }))
    return http.post(apis.agentletterLaunchImport, formData, { timeout: 1000 * 60 * 10 }).then((res) => {
      message.success('操作成功')
      const dataSource = res?.data ?? []
      this.setState({
        dataSource,
        loading: false,
        pagination: {
          current: 1,
          pageSize: 10,
          total: dataSource.length ?? 0,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '40'],
          showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        },
        selectedRows: dataSource,
        selectedRowKeys: dataSource.map(({ id }) => id)
      })
    })
  }

  private handDeleteRecord = record => {
    Modal.confirm({
      title: '删除',
      content: `确定删除经销商：${record.agentName}吗`,
      okType: 'danger',
      onOk: () => {
        this.setState((preState: IState) => {
          let dataSource = preState.dataSource.filter(item => item.id !== record.id)
          return {
            dataSource,
            selectedRowKeys: preState.selectedRowKeys.filter(item => item !== record.id),
            selectedRows: preState.selectedRows.filter(item => item.id !== record.id),
            pagination: {
              current: 1,
              pageSize: 10,
              total: dataSource.length ?? 0,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '30', '40'],
              showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
            },
          }
        })
      },
    })
  }

  private onSelectChange = (selectedRowKeys: number[], selectedRows: any[]) => {
    this.setState({ selectedRowKeys, selectedRows })
  }

  private onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      const { dataSource } = this.state
      this.setState({ selectedRows: dataSource, selectedRowKeys: dataSource.map(({ id }) => id) })
    } else {
      this.setState({ selectedRows: [], selectedRowKeys: [] })
    }
  }

  private onOk = e => {
    const { selectedRows = [] } = this.state
    this.props.onGetDataSource(selectedRows)
    e.close()
  }

  private getAreaList = (value: string) => {
    http
      .get(userApis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let treeDataList = res?.data?.children || []
        this.setState({ treeDataList })
      })
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  private handleSearch = (values: any) => {
    this.getTableData()
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [] }, () => {
      this.getTableData()
    })
  }

  private getTableData = async () => {
    // this.setState({ loading: true, selectedRowKeys: [], selectedRows: [] })
    this.setState({ loading: true })
    try {
      let list: any = await http.post(apis.getAllAgentInfo, {
        brandCode: this.props.brandCode,
        ...this.filterForm.getFieldsValue(),
      })
      const dataSource = list?.data ?? []
      this.setState({
        dataSource,
        loading: false,
        pagination: {
          current: 1,
          pageSize: 10,
          total: dataSource.length ?? 0,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '40'],
          showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        },
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}

interface IProps {
  brandCode: string
  dataSource: Record<string, any>[]
  onGetDataSource: (params: Record<string, any>[]) => void
}
interface IState {
  pagination: Record<string, any>
  dataSource: Record<string, any>[]
  loading: boolean
  treeDataList: Record<string, any>[]
  selectedRowKeys: number[]
  selectedRows: Record<string, any>[]
  searchValues?: {}
}
